package com.qili.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.druid.sql.visitor.functions.Char;
import com.alibaba.fastjson.JSONArray;
import com.qili.base.entity.CurrentMenu;
import com.qili.base.entity.CurrentRole;
import com.qili.base.entity.CurrentUser;
import com.qili.base.mapper.BaseMapper;
import com.qili.base.service.impl.BaseServiceImpl;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.jc.JcProject;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.sys.*;
import com.qili.entity.sys.dto.SysRoleUserDTO;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.ZxProject;
import com.qili.exception.MyException;
import com.qili.mapper.base.BaseDictMapper;
import com.qili.mapper.jc.JcProjectMapper;
import com.qili.mapper.supervisor.SupervisorProjectMapper;
import com.qili.mapper.sys.SysRoleUserMapper;
import com.qili.mapper.sys.SysUserMapper;
import com.qili.mapper.zx.ZxProjectMapper;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.*;
import com.qili.service.sys.MenuService;
import com.qili.service.sys.RoleService;
import com.qili.service.sys.RoleUserService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhuxiaomeng
 * @date 2017/12/4.
 * @email 154040976@qq.com
 */
@Slf4j
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    RoleService roleService;

    @Autowired
    RoleUserService roleUserService;

    @Autowired
    MenuService menuService;

    @Autowired
    UploadUtil uploadUtil;

    @Autowired
    BaseCompanyService companyService;

    @Autowired
    SysUserWorkExperienceService workExperienceService;

    @Autowired
    BaseDictService baseDictService;

    @Autowired
    BaseCompanyService baseCompanyService;

    @Autowired
    private SupervisorProjectMapper supervisorProjectMapper;
    @Autowired
    private  ZxProjectMapper  zxProjectMapper;
    @Autowired
    private JcProjectMapper jcProjectMapper;
    @Autowired
    private ZxProjectMapper ZxProjectMapper;
    @Autowired
    private SupervisorFileService supervisorFileService;
    @Autowired
    private ProjectLeaderService projectLeaderService;
    @Autowired
    private ProjectUnitConstructionService projectUnitConstructionService;

    @Autowired
    BaseDictMapper baseDictMapper;
    @Autowired
    SupervisorProjectModifiedRecordService modifiedRecordService;
    @Autowired
    SupervisorProjectPayService payService;

    private static final String ADMIN = "admin";

    public static SoftReference<ArrayList<String>> orgNameList = new SoftReference<ArrayList<String>>(new ArrayList<String>());

    @Override
    public BaseMapper<SysUser, String> getMappser() {
        return sysUserMapper;
    }


    @Override
    public SysUser login(String username) {
        return sysUserMapper.login(username);
    }


    @Override
    public int deleteByPrimaryKey(String id) {
        return sysUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(SysUser record) {
        return sysUserMapper.insert(record);
    }

    @Override
    public int insertSelective(SysUser record) {

        String pwd = Md5Util.getMD5(record.getPassword().trim(), record.getUsername().trim());
        record.setPassword(pwd);
        return super.insertSelective(record);
    }

    @Override
    public SysUser selectByPrimaryKey(String id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    public SysUserDTO selectUserById(String id) {
        return sysUserMapper.selectUserById(id);
    }

    @Override
    public int updateByPrimaryKeySelective(SysUser record) {
        return super.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(SysUser record) {
        return sysUserMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<SysRoleUser> selectByCondition(SysRoleUser sysRoleUser) {
        return sysRoleUserMapper.selectByCondition(sysRoleUser);
    }

    /**
     * 分页查询
     *
     * @param
     * @return
     */
    @Override
    public List<SysUser> selectListByPage(SysUser sysUser) {
        return sysUserMapper.selectListByPage(sysUser);
    }

    @Override
    public int count() {
        return sysUserMapper.count();
    }

    @Override
    public int add(SysUser user) {
        //密码加密
        String pwd = Md5Util.getMD5(user.getPassword().trim(), user.getUsername().trim());
        user.setPassword(pwd);
        user.setSource("003");
        return sysUserMapper.add(user);
    }

    @Override
    public JsonUtil delById(String id, boolean flag) {
        if (StringUtils.isEmpty(id)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil j = new JsonUtil();
        try {
            SysUser sysUser = selectByPrimaryKey(id);
            if (ADMIN.equals(sysUser.getUsername())) {
                return JsonUtil.error("超管无法删除");
            }
            SysRoleUser roleUser = new SysRoleUser();
            roleUser.setUserId(id);
            int count = roleUserService.selectCountByCondition(roleUser);
            if (count > 0) {
                return JsonUtil.error("账户已经绑定角色，无法删除");
            }
            if (flag) {
                //逻辑
                sysUser.setDelFlag(Byte.parseByte("1"));
                updateByPrimaryKeySelective(sysUser);
            } else {
                //物理
                sysUserMapper.delById(id);
            }
            j.setMsg("删除成功");
        } catch (MyException e) {
            j.setMsg("删除失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;

    }

    @Override
    public int checkUser(String username) {
        return sysUserMapper.checkUser(username);
    }

    @Override
    public List<Checkbox> getUserRoleByJson(String id) {
        List<SysRole> roleList = roleService.selectListByPage(new SysRole());
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserId(id);
        List<SysRoleUser> kList = selectByCondition(sysRoleUser);

        List<Checkbox> checkboxList = new ArrayList<>();
        Checkbox checkbox;
        for (SysRole sysRole : roleList) {
            checkbox = new Checkbox();
            checkbox.setId(sysRole.getId());
            checkbox.setName(sysRole.getRoleName());
            checkbox.setRemark(sysRole.getRemark());
            for (SysRoleUser sysRoleUser1 : kList) {
                if (sysRoleUser1.getRoleId().equals(sysRole.getId())) {
                    checkbox.setCheck(true);
                    break;
                }
            }
            checkboxList.add(checkbox);
        }
        return checkboxList;
    }

    @Override
    public int rePass(SysUser user) {
        return sysUserMapper.rePass(user);
    }

    @Override
    public List<SysUser> getUserByRoleId(String roleId) {
        return sysUserMapper.getUserByRoleId(roleId);
    }


    @Override
    public void setMenuAndRoles(String username) {
        SysUser s = new SysUser();
        s.setUsername(username);
        s = this.selectOne(s);
        CurrentUser currentUser = new CurrentUser(s.getId(), s.getUsername(), s.getAge(), s.getEmail(), s.getPhoto(), s.getRealName(),s.getNumTag(),s.getTags());
        Subject subject = Principal.getSubject();
        /*角色权限封装进去*/
        //根据用户获取菜单
        Session session = subject.getSession();
        if (null != session.getAttribute("roleSeted")) {
            session.removeAttribute("roleSeted");
            return;
        }
        List<SysMenu> menuList = menuService.getUserMenu(s.getId());
        JSONArray json = menuService.getMenuJsonByUser(menuList);
        session.setAttribute("menu", json);


        List<CurrentMenu> currentMenuList = new ArrayList<>();
        Set<SysRole> roleList = new HashSet<>();
        for (SysMenu m : menuList) {
            CurrentMenu currentMenu = new CurrentMenu();
            BeanUtil.copyNotNullBean(m, currentMenu);
            currentMenuList.add(currentMenu);
            roleList.addAll(m.getRoleList());
        }

        List<CurrentRole> currentRoleList = new ArrayList<>();

        for (SysRole r : roleList) {
            CurrentRole role = new CurrentRole();
            BeanUtil.copyNotNullBean(r, role);
            currentRoleList.add(role);
        }

        currentUser.setCurrentRoleList(currentRoleList);
        currentUser.setCurrentMenuList(currentMenuList);
        session.setAttribute("currentPrincipal", currentUser);
    }

    @Override
    public void setMenuAndRolesWhenRegist(SysUser user, List<String> rolelist) {
        for (int i = 0; i < rolelist.size(); i++) {
            String roleName = rolelist.get(i);
            //获取根据用户的供需类型获取初始角色列表
            Example example = new Example(SysRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.orEqualTo("roleName", roleName);
            List<SysRole> roleList = roleService.selectByExample(example);
            for (SysRole sr : roleList) {
                SysRoleUser roleuser = new SysRoleUser();
                roleuser.setUserId(user.getId());
                roleuser.setRoleId(sr.getId());
                List<SysRoleUser>  sysuserselect=roleUserService.select(roleuser);
                if (sysuserselect.size()==0) {
                    roleUserService.insert(roleuser);
                }
            }
        }
    }

    /**
     * 更新session头像
     */
    @Override
    public void updateCurrent(SysUser sysUser) {
        CurrentUser principal = Principal.getPrincipal();
        if (principal.getId().equals(sysUser.getId())) {
            //当前用户
            CurrentUser currentUse = Principal.getCurrentUse();
            Session session = Principal.getSession();
            currentUse.setPhoto(sysUser.getPhoto());
            session.setAttribute("currentPrincipal", currentUse);

        }
    }

    @Override
    public SysUser selectByEmail(String email) {
        return sysUserMapper.selectByEmail(email);
    }

    @Override
    public int updateById(String id, String passwordNew, String name) {
        String password = Md5Util.getMD5(passwordNew, name);
        return sysUserMapper.updateById(id, password);
    }

    @Override
    public SysUser selectById(String id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public int updateUser(SysUser sysUser) {
        return sysUserMapper.updateUser(sysUser);
    }

    @Override
    public int updateNum(SysUser sysUser) {
        return sysUserMapper.updateNum(sysUser);
    }

    @Override
    public List<SysUser> getUserDicts(SysUserDTO sysUser) {
        return sysUserMapper.getUserDicts(sysUser);
    }

    @Override
    public void selectUserYwTypeName(SysUserDTO user) {
        //查询所有的业务类型:
        List<BaseDict> dictByType = DictUtil.getDictByType(DictTypes.YW_TYPE);
        Map<String, String> maps = dictByType.stream().collect(Collectors.toMap(BaseDict::getBadtCode, BaseDict::getBadtName, (key1, key2) -> key2));
        String result = "";
        if (user.getYwType().contains(",")) {
            String[] split = user.getYwType().split(",");
            for (String s : split) {
                result += "".equals(result) ? maps.get(s) : "/" + maps.get(s);
            }
        } else {
            result = maps.get(user.getYwType());
        }
        user.setYwname(result);
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 判断该用户是否存在 某个角色
     * @Date:11:06 2020/12/10
     */
    public List<SysRoleUser> querySysRoleByRoleName(String userId, String roleName) {
        SysRoleUserDTO roleuserdto = new SysRoleUserDTO();
        roleuserdto.setRoleName(roleName);
        roleuserdto.setUserId(userId);
        List<SysRoleUser> sysRoleUserList = roleUserService.selectRoleUser(roleuserdto);
        return sysRoleUserList;
    }

    /**
     * @Author:Zhangshuo
     * @Description:更新tags
     * @param sysUser
     * @Date:13:32 2020-12-14
     */
    @Override
    public void updateTags(SysUser sysUser) {
        sysUserMapper.updateTags(sysUser);
    }

    @Override
    public JsonUtil checkSameTelephone(SysUser sysUser) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(true);
        if(StringUtils.isNotBlank(sysUser.getPhoneNumber())){
            SysUser samePhoneUser = new SysUser();
            samePhoneUser.setPhoneNumber(sysUser.getPhoneNumber());
            List<SysUser> select = sysUserMapper.select(samePhoneUser);
            if(select.size() > 0){
                if("001".equals(sysUser.getPersonType())){
                    jsonUtil.setMsg("注册失败!手机号不能重复!");
                }else{
                    jsonUtil.setMsg("注册失败!联系方式不能重复!");
                }
                jsonUtil.setFlag(false);
            }
        }
        return jsonUtil;
    }

    @Override
    public JsonUtil checkSameTelephoneWhenUpdate(SysUser sysUser) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(true);
        int count = sysUserMapper.getSamePhoneUsersWithoutMe(sysUser);
        if(count > 0){
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("更改失败!已经存在的手机号码");
            return jsonUtil;
        }
        return jsonUtil;
    }

    @Override
    public JsonUtil checkSameEmailWhenUpdate(SysUser sysUser) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(true);
        int count = sysUserMapper.getSameEmailUsersWithoutMe(sysUser);
        if(count > 0){
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("更改失败!已经存在的邮箱");
            return jsonUtil;
        }
        return jsonUtil;
    }

    /**
     * 不少于8个字符,并且是大写字母 小写字母  数字  特殊字符的至少三种
     * @param pwd
     * @return
     */
    @Override
    public boolean checkUserPassword(String pwd) {
        if(pwd.length() < 8){
            return false;
        }
        int alphaLower = 0;
        int alphaUpper = 0;
        int number = 0;
        int is_ = 0;
        for(int i=0;i<pwd.length();i++){
            char c = pwd.charAt(i);
            //如果是小写字母:
            if(CharUtils.isAsciiAlphaLower(c)){
                alphaLower = 1;
            }else if(CharUtils.isAsciiAlphaUpper(c)){
                alphaUpper = 1;
            }else if(CharUtils.isAsciiAlphanumeric(c)){
                number = 1;
            }else if (isSpecial(c)){
                is_ = 1;
            }else{
                return false;
            }
        }
        if((alphaLower + alphaUpper + number + is_) < 3){
            return false;
        }
        return true;
    }

    /**
     * 判断是否包含特殊字符
     * @param pwd
     * @return
     */
    private boolean isSpecial(char pwd){
        //特殊符号
        String REG_SYMBOL = ".*[~!@#$%^&*]+.*";
        String s = String.valueOf(pwd);
        if (s.matches(REG_SYMBOL)){
            return true;
        }
        return false;
    }

    @Override
    public String getJsdwglrCount() {
        int i = sysUserMapper.selectJsdwglrCount();
        if(i == 0){
            return "";
        }else if(i < 9999){
            return new DecimalFormat("0000").format(i);
        }else{
            return i+"";
        }
    }

    /**
     * 验证用户名是否重复,如果重复,那么取最后的数字后加1,然后返回
     * @param newUserName
     */
    public String checkAndHandlerSameNewUserName(String newUserName) {
        SysUser sameNameUser = new SysUser();
        sameNameUser.setUsername(newUserName);
        List<SysUser> select = select(sameNameUser);
        if(select.size() > 0){
            if(!CharUtils.isAsciiNumeric(newUserName.charAt(newUserName.length()-1))){
                newUserName = newUserName + "0001";
            }else{
                newUserName = StringUtil.getNextOne(newUserName);
            }
            return checkAndHandlerSameNewUserName(newUserName);
        }else{
            return newUserName;
        }
    }

    public String getNewUserName(String provinceName){
        //去掉省字
        provinceName = provinceName.replaceAll("省", "");
        //转换为拼音首字母
        String provinceShort = ChineseUtil.getAllFirstLetter(provinceName);
        //获取已经有多少个建设单位负责人了(方法内部已经加一了)
        String jsdwglrCount = getJsdwglrCount();
        //拼接用户名:
        return "admin"+provinceShort+jsdwglrCount;
    }

    @Override
    public List<SysUserDTO> selectProjectAdmin(String projectId) {
        return sysUserMapper.selectProjectAdmin(projectId);
    }

    @Override
    public List<SysUserDTO> selectUsefulUsers(SysUser user) {
        return sysUserMapper.selectUsefulUsers(user);
    }

    @Override
    public synchronized void setUserFilePath(SysUser user) {
        //source=001    user.company  == xxx      '正中信息总部'        人员信息资料    +    正中信息总部    +    工程部    +    0001张三
        //source=001    user.company != xxxx     人员信息资料    +    北京分公司     +    001王某
        //系统自行注册的供方/需方组织   或者是项目创建的         (source=003  personType=002) || source==002    系统注册企业    001xxx企业
        //系统自行注册人员:   source=003  personType=001    系统注册人员/0001张三01
        String source = user.getSource();
        if(StringUtils.isBlank(source)){
            throw new RuntimeException("创建正中用户资料路径时,用户注册方式缺失!");
        }
        if("002".equals(source) && StringUtils.isBlank(user.getGxType()) && StringUtils.isBlank(user.getPersonType())){
            //项目创建的承建单位,无法创建目录
            return ;
        }
        if(("003".equals(source)) && StringUtils.isBlank(user.getGxType())){
            throw new RuntimeException("创建用户资料路径时,供需类型没有设置!");
        }
        if(("003".equals(source)) && StringUtils.isBlank(user.getPersonType())){
            throw new RuntimeException("创建用户资料路径时,账号的个人/组织属性没有设置!");
        }


        StringBuffer FulluploadPath = new StringBuffer();
        String uploadPath = uploadUtil.getUploadPath();
        String userPath = uploadUtil.getUserPath();
        String userZzPath = uploadUtil.getUserZzPath();//人员信息资料
        String userRegistPersonPath = uploadUtil.getUserRegistPersonPath();
        String userRegistCompanyPath = uploadUtil.getUserRegistCompanyPath();
        FulluploadPath = FulluploadPath.append(uploadPath).append(userPath).append(File.separator);///上传路径/人员资质库/
        switch(source){
            case "001":
                String companyBcId = user.getCompanyName();
                if(StringUtils.isBlank(companyBcId)){
                    log.info(user.toString());
                    throw new RuntimeException("创建正中用户资料路径时,用户部门id缺失!");
                }
                String companyName = "";
                BaseCompany userCompany = new BaseCompany();
                SysUser dbUser = selectByPrimaryKey(user.getId());
                userCompany.setBcId(dbUser.getCompanyName());
                List<BaseCompany> select = companyService.select(userCompany);
                if(select!=null && select.size()>0){
                    companyName = select.get(0).getBcName();
                }else{
                    throw new RuntimeException("创建正中用户资料路径时,用户公司信息缺失!");
                }

                FulluploadPath = FulluploadPath.append(userZzPath); // /上传路径/人员资质库/人员信息资料
                //根据不同情况,获取用户人名目录所在目录:
                if("1564895".equals(companyBcId)){
                    if(null == user.getNowWork()){
                        //查询用户部门信息:
                        SysUserWorkExperience nowWork = new SysUserWorkExperience();
                        nowWork.setSuId(user.getId());
                        nowWork.setIfNow("1");
                        List<SysUserWorkExperience> select1 = workExperienceService.select(nowWork);
                        if(select1!=null && select1.size()>0){
                            user.setNowWork(select1.get(0));
                        }else{
                            throw new RuntimeException("创建人员资质库目录时,没有找到部门信息");
                        }

                    }
                    if(StringUtils.isBlank(user.getNowWork().getDeptCode())){
                        throw new RuntimeException("创建正中用户资料路径时,用户部门信息缺失!");
                    }else{
                        //根据部门字典code查询部门名称:
                        BaseDict deptBaseDict = new BaseDict();
                        deptBaseDict.setBadtTypecode(DictTypes.DEPT.getType());
                        deptBaseDict.setBadtCode(user.getNowWork().getDeptCode());
                        List<BaseDict> select1 = baseDictService.select(deptBaseDict);
                        if(select1 == null || select1.size() == 0 || StringUtils.isBlank(select1.get(0).getBadtName())){
                            throw new RuntimeException("创建正中用户资料路径时,用户部门信息缺失!");
                        }
                        user.getNowWork().setDeptName(select1.get(0).getBadtName());
                    }

                    FulluploadPath = FulluploadPath  //  /上传路径/人员资质库/人员信息资料/正中信息总部/xx部
                            .append(File.separator)
                            .append(companyName)
                            .append(File.separator)
                            .append(user.getNowWork().getDeptName());

                }else{
                    FulluploadPath = FulluploadPath  // /上传路径/人员资质库/人员信息资料/xx分公司
                            .append(File.separator)
                            .append(companyName);
                }

                File deptDirectory = new File(FulluploadPath.toString());
                String userDictoryFront = "0001";
                if(deptDirectory.exists() && deptDirectory.isDirectory()){
                    //获取当前目录下的所有目录个数:
                    int deptFileCount = getDeptFileCount(deptDirectory);
                    userDictoryFront = StringUtil.autoGenericCode((deptFileCount + 1) + "", 4);
                }
                FulluploadPath = FulluploadPath.append(File.separator)   // /上传路径/人员资质库/人员信息资料/       /0001张三
                        .append(userDictoryFront)
                        .append(user.getRealName());
                String fullUploadPathStr = FilePathUtil.doFileSeparator(FulluploadPath.toString());
                File userDirectory = new File(fullUploadPathStr);
                if(!userDirectory.exists()){
                    userDirectory.mkdirs();
                }
                String userInfoDic = fullUploadPathStr.substring(fullUploadPathStr.indexOf(File.separator+userZzPath));
                File userInfoDicFile = new File(userInfoDic);
                user.setInfoDic(userInfoDicFile.getPath());
                break;
            case "002":
            case "003":
                //根据类型   个人/组织来创建目录:
                if(StringUtils.isNotBlank(user.getPersonType())){
                    String userDicFront = "";
                    if("001".equals(user.getPersonType())){
                        //个人
                        FulluploadPath = FulluploadPath.append(userRegistPersonPath);  // /上传路径/人员资质库/系统注册人员
                        File userRegistPersonDictory = new File(FulluploadPath.toString());
                        if(userRegistPersonDictory.exists() && userRegistPersonDictory.isDirectory()){
                            String userDictoryByUserAndDictory = getUserDictoryByUserAndDictory(userRegistPersonDictory, user);
                            FulluploadPath = FulluploadPath.append(File.separator).append(userDictoryByUserAndDictory);
                        }else{
                            FulluploadPath = FulluploadPath.append(File.separator).append("0001"+user.getRealName()+"01");
                        }
                    }else if("002".equals(user.getPersonType())){
                        //组织
                        FulluploadPath = FulluploadPath.append(userRegistCompanyPath).append(File.separator);  // /上传路径/人员资质库/系统注册企业
                        File userRegistCompanyDic = new File(FulluploadPath.toString());
                        if(userRegistCompanyDic.exists() && userRegistCompanyDic.isDirectory()){
                            int dicCount = 0;
                            File[] files = userRegistCompanyDic.listFiles();
                            for(File file : files){
                                String fileName = file.getName();
                                if(file.isDirectory() && fileName.length()>4 && fileName.substring(4).equals(user.getCompanyName())){
                                    //有重名企业的,
                                    String thisFilePath = FulluploadPath.append(file.getName()).toString();
                                    thisFilePath = thisFilePath.substring(thisFilePath.indexOf(File.separator+userRegistCompanyPath));
                                    user.setInfoDic(thisFilePath);
                                    break ;
                                }
                                dicCount ++;
                            }
                            FulluploadPath = FulluploadPath.append(StringUtil.autoGenericCode((dicCount+1)+"",4)+user.getCompanyName());
                        }else{
                            FulluploadPath = FulluploadPath.append("0001"+user.getCompanyName());
                        }
                    }
                    String fullUploadPathStr2 = FilePathUtil.doFileSeparator(FulluploadPath.toString());
                    File finallyFile = new File(fullUploadPathStr2);
                    if(!finallyFile.exists()){
                        finallyFile.mkdirs();
                    }
                    String substring = "";
                    if("001".equals(user.getPersonType())){
                        substring = fullUploadPathStr2.substring(fullUploadPathStr2.indexOf(File.separator + userRegistPersonPath));
                    }else{
                        substring = fullUploadPathStr2.substring(fullUploadPathStr2.indexOf(File.separator + userRegistCompanyPath));
                    }
                    File file = new File(substring);
                    user.setInfoDic(file.getPath());
                }
                break;
        }
        //这里先更新一下用户数据库的docInfo字段:
        if(StringUtils.isNotBlank(user.getInfoDic()) && StringUtils.isNotBlank(user.getId())){
            String infoDic = user.getInfoDic();
            File infoDicFile = new File(infoDic);
            SysUser userDocInfoUser = new SysUser();
            userDocInfoUser.setId(user.getId());
            userDocInfoUser.setInfoDic(infoDicFile.getPath());
            updateByPrimaryKeySelective(userDocInfoUser);
        }
    }

    /**
     * 获取 自行注册用户资料目录名称
     * 假如用户真实姓名为张三
     * 如果目标目录里面有 1001张三01  那么返回1002张三02 否则返回1002张三01
     * @param userRegistPersonDictory
     * @param user
     * @return
     */
    private String getUserDictoryByUserAndDictory(File userRegistPersonDictory, SysUser user) {

        int count = 0;
        int newDictoryInd = 1;
        String userName = user.getRealName();
        if(userRegistPersonDictory.exists() && userRegistPersonDictory.isDirectory()){
            File[] files = userRegistPersonDictory.listFiles();
            for(File file : files){
                //文件名称
                if(file.isDirectory()){
                    count++;
                    String fileName = file.getName();
                    String userNameFromFileName = fileName.substring(4,fileName.length()-2);
                    if(userNameFromFileName.equals(userName)){
                        newDictoryInd ++;
                    }
                }
            }
            return StringUtil.autoGenericCode((count+1)+"",4)+userName+StringUtil.autoGenericCode(newDictoryInd+"",2);
        }
        return "";
    }


    private int getDeptFileCount(File deptFile) {
        int count = 0;
        if(deptFile.exists()){
            File[] files = deptFile.listFiles();
            for(File file : files){
                if(file.isDirectory()){
                    count ++;
                }
            }
        }
        return count;
    }

    public void updateUserNowWork(SysUser sysUser){
        if(sysUser.getNowWork()!=null){
            SysUserWorkExperience nowWork = sysUser.getNowWork();
            if(StringUtils.isBlank(nowWork.getSuweId())){
                //看看数据库有没有：
                SysUserWorkExperience dbWorkExperience = new SysUserWorkExperience();
                dbWorkExperience.setSuId(sysUser.getId());
                dbWorkExperience.setIfNow("1");
                List<SysUserWorkExperience> select = workExperienceService.select(dbWorkExperience);
                if(select!=null && select.size()>0){
                    nowWork.setSuweId(select.get(0).getSuweId());
                    workExperienceService.updateByPrimaryKeySelective(nowWork);
                    return ;
                }
                nowWork.setSuweId(null);
                nowWork.setIfNow("1");
                nowWork.setSuId(sysUser.getId());
                workExperienceService.insertSelective(nowWork);
            }else{
                workExperienceService.updateByPrimaryKeySelective(nowWork);
            }
        }
    }

    @Override
    public void updateUserAuditStatus(String userId,String auditStatus,String reason) {
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(auditStatus)){
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setAuditStatus(auditStatus);
            if(StringUtils.isNotBlank(reason)){
                sysUser.setAuditFailReason(reason);
            }
            updateByPrimaryKeySelective(sysUser);
        }else{
            log.warn("更改用户状态时,参数异常");
        }
    }

  /**
  * @Author:zhaoyongke
  * @Description:判断用户是否含有某个角色
  * @param permission
  * @Date:11:38 2021/2/20
  */
 public Boolean isHasPermission(String permission){
     Boolean  ishas=false;
     SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
     //根据用户获取角色 根据角色获取所有按钮权限
     CurrentUser cUser = (CurrentUser) Principal.getSession().getAttribute("currentPrincipal");
     for (CurrentRole cRole : cUser.getCurrentRoleList()) {
         info.addRole(cRole.getRoleName());
     }
     for (CurrentMenu cMenu : cUser.getCurrentMenuList()) {
         if (!StringUtils.isEmpty(cMenu.getPermission())) {
             if(permission.equals(cMenu.getPermission())){
                 ishas=true;
                 break;
             }
         }
     }
     return ishas;
 }

    @Override
    public StringBuffer buldImportSqtj(MultipartFile file, StringBuffer message) {
        // 1. 读取文件内容
        InputStream is = null;
        List<List> importResult = null;
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        try {
            is = file.getInputStream();
            if("xls".equals(suffix)){
                importResult= ExcelUtil.readXls3(is);
            }else{
                importResult= ExcelUtil.readXlsx3(is);
            }

            // 2. 校验excel导入的信息是否有误
            Map<String,String> dataCorr = getHeader(importResult, message);
            if (StringUtils.isNotBlank(message)) {
                return message;
            }
            checkExcel(importResult,message);

            // 3. excel没有错误情况保存
            if (StringUtils.isBlank(message)) {

                // 保存用户数据
                saveUserInfo(importResult);
            }else{
                return message;
            }

        } catch (IOException e) {
            e.printStackTrace();
            message.setLength(0);
            message.append("网络出错，请稍后重试！");
            return message;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("返回的错误信息:"+message.toString());
        return message;
    }

    @Override
    public StringBuffer importUserRoles(MultipartFile file, StringBuffer message) {
        // 1. 读取文件内容
        InputStream is = null;
//        List<List> importResult = null;
        List<Map<String,List<String>>> importResult = null;
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        try {
            is = file.getInputStream();
            if("xls".equals(suffix)){
                importResult= ExcelUtil.UserRolesreadXls3(is);
            }else{
                importResult= ExcelUtil.UserRolesReadXlsx(is);
            }
            // 保存数据
            if (!importResult.isEmpty()){
                // 遍历最外层list集合
                for (Map<String, List<String>> importListMap : importResult) {
                    // 遍历内层Map集合
                    for (Map.Entry<String, List<String>> entry : importListMap.entrySet()) {
                        // 用户编码
                        String userName = entry.getKey();
                        // 用户对应的角色编码集合
                        List<String> list = entry.getValue();
                        // 现根据key查询出当前用户
                        SysUser user = sysUserMapper.selectUser(userName);
                        if (user == null){
                            message.append("没有此用户信息，用户编码为：" + userName);
                            return message;
                        }
                        // 根据用户id删除用户角色对应表
                        SysRoleUser roleUser = new SysRoleUser();
                        roleUser.setUserId(user.getId());
                        sysRoleUserMapper.delete(roleUser);
                        // 更新用户角色对应表
                        if(list != null && list.size() > 0){
                            for (String roleName : list) {
                                SysRoleUser sysRoleUser = new SysRoleUser();
                                sysRoleUser.setUserId(user.getId());
                                // 查询当前用户角色编码的id
                                SysRole sysRole = new SysRole();
                                sysRole.setRoleName(roleName);
                                List<SysRole> select = roleService.select(sysRole);
                                if(select != null && select.size() > 0){
                                    sysRoleUser.setRoleId(select.get(0).getId());
                                    // 更新表
                                    sysRoleUserMapper.insert(sysRoleUser);
                                }


                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            message.setLength(0);
            message.append("网络出错，请稍后重试！");
            return message;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("返回的错误信息:"+message.toString());
        return message;
    }

    private void saveUserInfo(List<List> importResult){
        for (int i = 1; i < importResult.size(); i++) {
            List row = importResult.get(i);
            // 2.1 用户真实名称
            String realName = ((String) row.get(0)).replaceAll("\\s", "");
            // 2.2 所属公司
            String orgName = ((String) row.get(1)).replaceAll("\\s", "");
            // 2.3 部门
            String deptName = ((String) row.get(2)).replaceAll("\\s", "");
            // 2.4 用户名
            String userName = ((String) row.get(3)).replaceAll("\\s", "");
            if(StringUtils.isBlank(realName) && StringUtils.isBlank(orgName) && StringUtils.isBlank(deptName)
                    && StringUtils.isBlank(userName) ){
                continue;
            }

            SysUser user = new SysUser();
            user.setUsername(userName);
            user.setRealName(realName);
            //根据公司名称获取公司对应的id:
            BaseCompany company = new BaseCompany();
            company.setBcName(orgName);
            List<BaseCompany> select1 = baseCompanyService.select(company);
            if(CollectionUtil.isNotEmpty(select1)){
                user.setCompanyName(select1.get(0).getBcId());
            }
            user.setPassword("12345678");
            user.setGxType("001");
            user.setYwType("100");
            user.setPersonType("001");
            user.setCreateBy(CommonUtil.getUserId());
            user.setCreateDate(DateUtil.getCurrentDateTime());
            user.setSource("001");
            switch (deptName){
                case "工程部":
                    user.setYwType("001");
                    break;
                case "咨询部":
                    user.setYwType("002");
                    break;
                case "检测部":
                    user.setYwType("003");
                    break;
                case "市场部":
                    user.setGxType("002");
                    break;
            }
            saveUserFromFile(user);
            if(StringUtils.isNotBlank(deptName)){
                //根据字典查编号
                BaseDict deptDict = new BaseDict();
                deptDict.setBadtTypecode(DictTypes.DEPT.getType());
                deptDict.setBadtName(deptName);
                List<BaseDict> select = baseDictService.select(deptDict);
                if(select!=null || select.size()>0){
                    BaseDict baseDict = select.get(0);
                    if(StringUtils.isNotBlank(baseDict.getBadtCode())){
                        SysUserWorkExperience nowWork = new SysUserWorkExperience();
                        nowWork.setSuId(user.getId());
                        nowWork.setIfNow("1");
                        nowWork.setDeptCode(baseDict.getBadtCode());
                        workExperienceService.insertSelective(nowWork);
                    }
                }
            }
        }
    }

    private void saveUserFromFile(SysUser user) {
        user.setId(IdUtil.simpleUUID());
        String pwd = Md5Util.getMD5(user.getPassword().trim(), user.getUsername().trim());
        user.setPassword(pwd);
        sysUserMapper.saveUserFromFile(user);
        setUserFilePath(user);
    }

    @Override
    public boolean checkUserOrg(String orgName) {
        ArrayList<String> orgNames = orgNameList.get();
        if(orgNames == null || orgNames.size() == 0){
            List<BaseCompany> baseCompanies = baseCompanyService.selectAll();
            orgNames = baseCompanies.stream().collect(ArrayList<String>::new, (list1, val) -> list1.add(val.getBcName()), (list1, list2) -> list1.addAll(list2));
        }
        return orgNames.contains(orgName);
    }

    /**
     * 获得表头以及列位置
     * @param importResult
     * @param message
     * @return
     */
    private Map<String,String> getHeader(List<List> importResult, StringBuffer message){
        Map<String,String> dataCorr = new HashMap<String,String>();
        //获取表头
        List row = importResult.get(0);
        if (row.size() < 4) {
            message = message.append("您的excel表头列数不全!<br/>");
        }

        String o = "姓名,所属公司,部门,用户名,";
        for(int i=0;i<row.size();i++){
            String key = (row.get(i)+"").replaceAll("\\s", "");
            o = o.replace(key+",", "");
            if(key.length()!=0){
                if(dataCorr.get(key)==null){
                    dataCorr.put(key, i+"");
                }else{
                    dataCorr.put(key, dataCorr.get(key)+"-"+i);
                }
            }
        }
        // 判断是否要求列都有以及存在表头文字相同的列，校验表头
        StringBuffer re = new StringBuffer();
        if(o.length()!=0){
            message = message.append("您的excel表头列缺少“"+o+"”列!<br/>");
        }
        for(String key: dataCorr.keySet()){
            if(dataCorr.get(key).contains("-")){
                re.append(key+",");
            }
        }
        if(StringUtils.isNotBlank(re.toString())){
            message = message.append("您的excel表头存在重复列“"+re+"”!<br/>");
        }
        return dataCorr;
    }

    /**
     * 校验传入的每一行信息
     *
     * @param importResult
     * @param message
     * @return
     */
    private List<List> checkExcel(List<List> importResult, StringBuffer message) {

        //存储新用户名称以及对应的行号集合
        Map<String,ArrayList<String>> newUserNameMap = new HashMap();

        //  对excel的每一行的列数做判断
        List row = new ArrayList();
        for (int i = 1; i < importResult.size(); i++) {

            row = importResult.get(i);
            // 2.1 用户真实名称
            String realName = ((String) row.get(0)).replaceAll("\\s", "");
            // 2.2 所属公司
            String orgName = ((String) row.get(1)).replaceAll("\\s", "");
            // 2.3 部门
            String deptName = ((String) row.get(2)).replaceAll("\\s", "");
            // 2.4 用户名
            String userName = ((String) row.get(3)).replaceAll("\\s", "");

            // 如果信息都为空则此行数据无效
            if(StringUtils.isBlank(realName) && StringUtils.isBlank(orgName) && StringUtils.isBlank(deptName)
                    && StringUtils.isBlank(userName)){
                continue;
            }
            if(StringUtils.isBlank(realName)){
                message.append("第"+(i+1)+"行，姓名为空！<br/>");
                continue;
            }
            if(StringUtils.isNotBlank(realName) && realName.length()>20){
                message.append("第"+(i+1)+"行，姓名超长！<br/>");
                continue;
            }
            if(StringUtils.isBlank(orgName)){
                message.append("第"+(i+1)+"行，所属公司为空！<br/>");
                continue;
            }
            if(StringUtils.isNotBlank(orgName) && orgName.length()>20){
                message.append("第"+(i+1)+"行，所属公司超长！<br/>");
                continue;
            }
            if(StringUtils.isBlank(deptName)){
                message.append("第"+(i+1)+"行，部门为空！<br/>");
                continue;
            }
            if(StringUtils.isNotBlank(deptName) && deptName.length()>20){
                message.append("第"+(i+1)+"行，部门超长！<br/>");
                continue;
            }
            if(StringUtils.isBlank(userName)){
                message.append("第"+(i+1)+"行，用户名为空！<br/>");
                continue;
            }
            if(StringUtils.isNotBlank(userName) && userName.length()>20){
                message.append("第"+(i+1)+"行，用户名超长！<br/>");
                continue;
            }
            if(!checkUserOrg(orgName)){
                message.append("第"+(i+1)+"行，不存在的所属公司名称！<br/>");
                continue;
            }

            if(!DictUtil.checkDic(DictTypes.DEPT.getType(),deptName)){
                message.append("第"+(i+1)+"行，不存在的部门名称！<br/>");
                continue;
            }

            ArrayList<String> userNameIndexList = newUserNameMap.get(userName);
            if(userNameIndexList != null && userNameIndexList.size()>0){
                String collect = userNameIndexList.stream().map(String::valueOf).collect(Collectors.joining(","));
                message.append("第"+(i+1)+"行，跟第 "+collect+"行用户名重复！<br/>");
                continue;
            }else{
                if(checkUser(userName) > 0){
                    message.append("第"+(i+1)+"行，已经存在的用户名！<br/>");
                    continue;
                }
            }
        }
        return importResult;
    }

    /**
    * @Author:zhaoyongke
    * @Description: 获取用户角色
    * @param projectId
    * @Date:11:21 2021/2/25
    */
    @Override
    public String getUserRole(String projectId) {
        String rolename="";
        //获取当前用户的角色
        String userId = CommonUtil.getUserId();
        SupervisorProject supervisorProject = supervisorProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(监理单位)
        String projectManager = supervisorProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        //总监理工程师
        String  zjl=supervisorProject.getSupervisorEngineer();
        if (userId.equals(zjl)) {
            /*总监理*/
            rolename="zjlgcs";
            return rolename;
        }
        //监理工程师
        String  jl=supervisorProject.getSecondSupervisorEngineer();
        if(StringUtil.isNotBlank(jl)){
            if (jl.indexOf(userId) != -1) {
                /*监理工程师*/
                rolename="jlgcs";
                return rolename;
            }
        }

        //技术负责人
        String technologyPerson= supervisorProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jsfzr";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUser(projectId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        /*判断是否是承建单位*/
        Boolean iscj = projectUnitConstructionService.isCjUser(projectId);
        if (iscj){
            rolename="cj";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectProjectAdmin(projectId);
        if(sysUserDTOS!=null){
            SysUserDTO admin =new SysUserDTO();
            if(sysUserDTOS.size()>0){
                admin = sysUserDTOS.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }
        // 工程部经理
        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
            rolename="gcbjl";
            return rolename;
        }
        // 公司管理层
        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
            rolename="gsgc";
            return rolename;
        }
        // 质控人员角色
        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
            rolename="zkry";
            return rolename;
        }
        // 管理员
        if (com.qili.core.shiro.Principal.hasRole("admin")) {
            rolename="admin";
            return rolename;
        }



        return rolename;
    }


    /**
     * @Author:zhaoyongke
     * @Description: 获取用户角色 app
     * @param projectId
     * @Date:11:21 2021/2/25
     */
    @Override
    public String getUserRoleJlApp(String projectId,String userId) {
        String rolename="";
        //获取当前用户的角色
        SupervisorProject supervisorProject = supervisorProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(监理单位)
        String projectManager = supervisorProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        //总监理工程师
        String  zjl=supervisorProject.getSupervisorEngineer();
        if (userId.equals(zjl)) {
            /*总监理*/
            rolename="zjlgcs";
            return rolename;
        }
        //监理工程师
        String  jl=supervisorProject.getSecondSupervisorEngineer();
        if(StringUtil.isNotBlank(jl)){
            if (jl.indexOf(userId) != -1) {
                /*监理工程师*/
                rolename="jlgcs";
                return rolename;
            }
        }

        //技术负责人
        String technologyPerson= supervisorProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jsfzr";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUserJlApp(projectId,userId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        /*判断是否是承建单位*/
        Boolean iscj = projectUnitConstructionService.isCjUserJlApp(projectId,userId);
        if (iscj){
            rolename="cj";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectProjectAdmin(projectId);
        if(sysUserDTOS!=null){
            SysUserDTO admin =new SysUserDTO();
            if(sysUserDTOS.size()>0){
                admin = sysUserDTOS.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }

        // 工程部经理
        SysRoleUserDTO  sysRoleUserDTO=new SysRoleUserDTO();
        sysRoleUserDTO.setRoleName("gcbjl");
        sysRoleUserDTO.setUserId(userId);
        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.selectRoleUser(sysRoleUserDTO);
        if(sysRoleUsers!=null){
            if(sysRoleUsers.size()>0){
                rolename="gcbjl";
                return rolename;
            }

        }

        // 工程部经理
//        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
//            rolename="gcbjl";
//            return rolename;
//        }

        // 公司管理层
        SysRoleUserDTO  sysRoleUserDTOgl=new SysRoleUserDTO();
        sysRoleUserDTOgl.setRoleName("gsgc");
        sysRoleUserDTOgl.setUserId(userId);
        List<SysRoleUser> sysRoleUsersgl = sysRoleUserMapper.selectRoleUser(sysRoleUserDTOgl);
        if(sysRoleUsersgl!=null){
            if(sysRoleUsersgl.size()>0){
                rolename="gsgc";
                return rolename;
            }

        }
        // 公司管理层
//        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
//            rolename="gsgc";
//            return rolename;
//        }


       // 质控人员角色
        SysRoleUserDTO  sysRoleUserDTOzk=new SysRoleUserDTO();
        sysRoleUserDTOzk.setRoleName("zkjsry");
        sysRoleUserDTOzk.setUserId(userId);
        List<SysRoleUser> sysRoleUserzk = sysRoleUserMapper.selectRoleUser(sysRoleUserDTOzk);
        if(sysRoleUserzk!=null){
            if(sysRoleUserzk.size()>0){
                rolename="zkry";
                return rolename;
            }

        }


        // 质控人员角色
//        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
//            rolename="zkry";
//            return rolename;
//        }
        // 管理员

        SysRoleUserDTO  sysRoleUserDTOadmin=new SysRoleUserDTO();
        sysRoleUserDTOadmin.setRoleName("admin");
        sysRoleUserDTOadmin.setUserId(userId);
        List<SysRoleUser> sysRoleUseradmin = sysRoleUserMapper.selectRoleUser(sysRoleUserDTOadmin);
        if(sysRoleUseradmin!=null){
            if(sysRoleUseradmin.size()>0){
                rolename="admin";
                return rolename;
            }

        }
//        if (com.qili.core.shiro.Principal.hasRole("admin")) {
//            rolename="admin";
//            return rolename;
//        }



        return rolename;
    }


    /**
     * @Author:zhaoyongke
     * @Description: 获取用户角色  咨询
     * @param projectId
     * @Date:11:21 2021/2/25
     */
    public String getUserRoleZx(String projectId) {
        String rolename="";
        //获取当前用户的角色
        String userId = CommonUtil.getUserId();
        ZxProject zxProject = zxProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(咨询单位)
        String projectManager = zxProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        // 行业负责人
        String  induper=zxProject.getIndustryPerson();
        if (userId.equals(induper)) {
            /*行业负责人*/
            rolename="zxdwhyfzr";
            return rolename;
        }
        //技术负责人
        String technologyPerson= zxProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jsfzr";
            return rolename;
        }
        //咨询顾问
        String zxgw= zxProject.getZxAdviser();
        if (userId.equals(zxgw)) {
            /*技术负责人*/
            rolename="zxgw";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUser(projectId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectProjectAdmin(projectId);
        if(sysUserDTOS!=null){
            SysUserDTO admin =new SysUserDTO();
            if(sysUserDTOS.size()>0){
                admin = sysUserDTOS.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }
        // 工程部经理
        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
            rolename="gcbjl";
            return rolename;
        }
        // 公司管理层
        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
            rolename="gsgc";
            return rolename;
        }
        // 质控人员角色
        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
            rolename="zkry";
            return rolename;
        }
        // 管理员
        if (com.qili.core.shiro.Principal.hasRole("admin")) {
            rolename="admin";
            return rolename;
        }



        return rolename;
    }

    /**
     * @Author:zhaoyongke
     * @Description: 咨询获取用户角色
     * @param projectId
     * @Date:11:21 2021/2/25
     */
    public String getZxUserRole(String projectId) {
        String rolename="";
        //获取当前用户的角色
        String userId = CommonUtil.getUserId();
        ZxProject supervisorProject = ZxProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(监理单位)
        String projectManager = supervisorProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        //总监理工程师
        String  zjl=supervisorProject.getSupervisorEngineer();
        if (userId.equals(zjl)) {
            /*总监理*/
            rolename="zjlgcs";
            return rolename;
        }
        //技术负责人
        String technologyPerson= supervisorProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jsfzr";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUser(projectId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        /*判断是否是承建单位*/
        Boolean iscj = projectUnitConstructionService.isCjUser(projectId);
        if (iscj){
            rolename="cj";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectProjectAdmin(projectId);
        if(sysUserDTOS!=null){
            SysUserDTO admin =new SysUserDTO();
            if(sysUserDTOS.size()>0){
                admin = sysUserDTOS.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }
        // 工程部经理
        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
            rolename="gcbjl";
            return rolename;
        }
        // 公司管理层
        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
            rolename="gsgc";
            return rolename;
        }
        // 质控人员角色
        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
            rolename="zkry";
            return rolename;
        }
        // 管理员
        if (com.qili.core.shiro.Principal.hasRole("admin")) {
            rolename="admin";
            return rolename;
        }



        return rolename;
    }
    @Override
    public int checkUserEmail(String email) {
        return sysUserMapper.checkUserEmail(email);
    }

    @Override
    public String getUserRoleJc(String projectId) {
        String rolename="";
        //获取当前用户的角色
        String userId = CommonUtil.getUserId();
        JcProject jcProject = jcProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(咨询单位)
        String projectManager = jcProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        // 检测工程师
        String  induper=jcProject.getJcAdviser();
        if (induper.indexOf(userId)  != -1) {
            /*检测工程师*/
            rolename="jcgw";
            return rolename;
        }
        //技术负责人
        String technologyPerson= jcProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jcjsfzr";
            return rolename;
        }
        //授权签字人
        String sqqzr= jcProject.getIndustryPerson();
        if (userId.equals(sqqzr)) {
            /*技术负责人*/
            rolename="sqqzr";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUser(projectId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectProjectAdmin(projectId);
        if(sysUserDTOS!=null){
            SysUserDTO admin =new SysUserDTO();
            if(sysUserDTOS.size()>0){
                admin = sysUserDTOS.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }
        // 工程部经理
        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
            rolename="gcbjl";
            return rolename;
        }
        // 公司管理层
        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
            rolename="gsgc";
            return rolename;
        }
        // 质控人员角色
        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
            rolename="zkry";
            return rolename;
        }
        // 管理员
        if (com.qili.core.shiro.Principal.hasRole("admin")) {
            rolename="admin";
            return rolename;
        }



        return rolename;
    }


    @Override
    public String getJcUserRole(String projectId) {
        String rolename="";
        //获取当前用户的角色
        String userId = CommonUtil.getUserId();
        JcProject supervisorProject = jcProjectMapper.selectByPrimaryKey(projectId);
        //项目经理Id(监理单位)
        String projectManager = supervisorProject.getProjectManagerPerson();
        if (userId.equals(projectManager)) {
            /*项目经理*/
            rolename="xmjl";
            return rolename;
        }
        //总监理工程师
        String  zjl=supervisorProject.getSupervisorEngineer();
        if (userId.equals(zjl)) {
            /*总监理*/
            rolename="zjlgcs";
            return rolename;
        }
        //技术负责人
        String technologyPerson= supervisorProject.getTechnologyPerson();
        if (userId.equals(technologyPerson)) {
            /*技术负责人*/
            rolename="jsfzr";
            return rolename;
        }

        /*判断是否是业主单位*/
        Boolean isyz = projectLeaderService.isYzUser(projectId);
        if (isyz) {
            rolename="yz";
            return rolename;
        }
        /*判断是否是承建单位*/
        Boolean iscj = projectUnitConstructionService.isCjUser(projectId);
        if (iscj){
            rolename="cj";
            return rolename;
        }
        // 判断业主单位管理员
        List<SysUserDTO> adminlist = sysUserMapper.selectProjectAdmin(projectId);
        if(adminlist!=null){
            SysUserDTO  admin=new SysUserDTO();
            if(adminlist.size()>0){
                admin=adminlist.get(0);
                if(CommonUtil.getUserId().equals(admin.getId())){
                    rolename="jsdwglry";
                    return rolename;
                }
            }

        }
        // 工程部经理
        if (com.qili.core.shiro.Principal.hasRole("gcbjl")) {
            rolename="gcbjl";
            return rolename;
        }
        // 公司管理层
        if (com.qili.core.shiro.Principal.hasRole("gsgc")) {
            rolename="gsgc";
            return rolename;
        }
        // 质控人员角色
        if (com.qili.core.shiro.Principal.hasRole("zkjsry")) {
            rolename="zkry";
            return rolename;
        }
        // 管理员
        if (com.qili.core.shiro.Principal.hasRole("admin")) {
            rolename="admin";
            return rolename;
        }



        return rolename;
    }

    @Override
    public List<String> selectUserIdListForPushMsg(String applicantId) {
        return sysUserMapper.selectUserIdListForPushMsg(applicantId);
    }

    @Override
    public SysUser phoneLogin(String phone) {
        return sysUserMapper.phoneLogin(phone);
    }

    @Override
    public int updateUserPassWordByPhone(String phoneNumber, String password) {
        return sysUserMapper.updatePassWordByPhone(phoneNumber,password);
    }

    @Override
    public int updatePasswordUsername(String username, String password) {
        return sysUserMapper.updatePasswordUsername(username,password);
    }

    @Override
    public SysUser selectUser(String username) {
        return sysUserMapper.selectUser(username);
    }

    @Override
    public  List<SysRoleUserDTO> selectRoleUserByUser(SysRoleUserDTO dto){
        List<SysRoleUserDTO> sysRoleUsers = sysRoleUserMapper.selectRoleUserByUser(dto);
        return sysRoleUsers;

    }

    @Override
    public List<SysUserDTO> selectExportUsers(SysUserDTO dto) {
        return sysUserMapper.selectExportUsers(dto);
    }


}
